import requests
import json
import pandas as pd
import requests
import json
import datetime
import time

headers = json.loads(r'''{
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Cache-Control": "max-age=0",
    "Connection": "keep-alive",
    "Content-Length": "317",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Cookie": "searchlist=searchlisttop=0; _abtest_userid=8acd19cf-eed4-4003-9798-09b853ecea23; MKT_Pagesource=PC; _RSG=rEaiXomkHlFcTT8sROMRn9; _RDG=2894910ed9557729900c27b931efc61941; _RGUID=fbd1bb0c-a1b2-43b5-9c5b-5986f621d766; _fpacid=09031046311358487592; GUID=09031046311358487592; traceExt=campaign=CHNbaidu81&adid=index; _RF1=36.27.5.185; cticket=B2C46C186810D97621A00F12F5F3CB4EC84251572DBF34AA579A9EF2DEDF8037; DUID=u=A0D63949572832465A998732AE73AFBB&v=0; IsNonUser=F; ticket_ctrip=uoeOwviAJ6VQEgTNwLuTqSV9j/bS+aOP3Riia1P+kyQbgkQZsD2gibEbkYhyWHIdCcaIzFcoGyvpZI5x4SEYsualULDiWxVQi6fbNceaIjNacVL4y5tBHRGAq+ECIk5GxRb/7vfILeV+2uOCd5XTCP+feU2ylAi7FQ86WuGvLX50brVPdbdBEs7egpaOrZTRYAXOOrIrJeBleS3hWq+70ETGWg3Y4hPZQksQs7b4AhZTad+a/GnjUC+uaMgxdafWFeVaDWVAwKjNpMpvnddqhRdACe4Yl3CoglCNk+dzN2f3LNeexDAy9hIAtIXEsdox; corpid=; corpname=; CtripUserInfo=VipGrade=0&UserName=&NoReadMessageCount=0&U=391E96138E606383B50FFBD1E20AF349; AHeadUserInfo=VipGrade=0&UserName=&NoReadMessageCount=0&U=391E96138E606383B50FFBD1E20AF349; LoginStatus=1%7c; TraceSession=1383495446; ASP.NET_SessionSvc=MTAuOC4xODkuNjF8OTA5MHxqaW5xaWFvfGRlZmF1bHR8MTUyNjU0OTk3OTY0MQ; Union=SID=155952&AllianceID=4897&OUID=baidu81|index|||; Session=SmartLinkCode=U155952&SmartLinkKeyWord=&SmartLinkQuary=&SmartLinkHost=&SmartLinkLanguage=zh; _jzqco=%7C%7C%7C%7C%7C1.1483656233.1531962586386.1532324697770.1532325886962.1532324697770.1532325886962.0.0.0.20.20; __zpspc=9.7.1532325886.1532325886.1%231%7Cbaidu%7Ccpc%7Cbaidu81%7C%25E6%2590%25BA%25E7%25A8%258B%7C%23; FD_SearchHistorty={\"type\":\"S\",\"data\":\"S%24%u5317%u4EAC%28BJS%29%24BJS%242018-07-24%24%u4E0A%u6D77%28SHA%29%24SHA%24%24%24\"}; _bfa=1.1531962577671.27djnt.1.1532047811172.1532324682000.5.54.10320605175; _bfs=1.9; Mkt_UnionRecord=%5B%7B%22aid%22%3A%221881%22%2C%22timestamp%22%3A1532325670834%7D%2C%7B%22aid%22%3A%224897%22%2C%22timestamp%22%3A1532325892229%7D%5D",
    "Host": "trains.ctrip.com",
    "If-Modified-Since": "Thu, 01 Jan 1970 00:00:00 GMT",
    "Origin": "http://trains.ctrip.com",
    "Referer": "http://trains.ctrip.com/TrainBooking/Search.aspx?from=beijing&to=shanghai&day=2018-07-24&number=&fromCn=%B1%B1%BE%A9&toCn=%C9%CF%BA%A3",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}''')

datacol = {0:'爬虫时间',1:'当前日期',2:'出发城市',3:'到达城市',4:'出发时点',5:'到达时点',6:'历时',7:'始发站',8:'到达站',9:'车型'}

class xc_demo():
    def __init__(self):
        self.url = "http://trains.ctrip.com/TrainBooking/Ajax/SearchListHandler.ashx?Action=getSearchList"
        self.mylist = []

    def getContent(self,times):
        print(f'正在获取{times}')
        aa = {"IsBus":"false","Filter":"0","Catalog":"","IsGaoTie":"false","IsDongChe":"false","CatalogName":"","DepartureCity":"beijing","ArrivalCity":"shanghai","HubCity":"","DepartureCityName":"北京","ArrivalCityName":"上海","DepartureDateReturn":times,"DepartureDate":times}
        data = {"value":json.dumps(aa)}
        resp = requests.post(self.url, data=data, headers=headers)
        # print(resp.text)
        if resp:
            myjson = json.loads(resp.text)
            for aa in myjson['TrainItemsList']:
                stime = aa['StratTime']
                etime = aa['EndTime']
                alltime = aa['TakeTime']
                splace = aa['StartStationName']
                eplace = aa['EndStationName']
                Tno = aa['TrainName']
                list1 = [time.strftime("%Y/%m/%d - %H:%M:%S"),times,'北京','上海',stime,etime,alltime,splace,eplace,Tno]
                for i in aa['SeatBookingItem']:
                    num = i['Inventory']
                    name = i['SeatName']
                    price = i['Price']
                    list1.append(name + " " + str(price) + " " + str(num))
                self.mylist.append(list1)


    def start(self):
        # self.getContent('2018-07-26')
        try:
            now = datetime.datetime.now()
            for i in range(15,45):
                delta = datetime.timedelta(days=i)
                n_days = now + delta
                self.getContent(n_days.strftime('%Y-%m-%d'))
            # print(self.mylist)
            df = pd.DataFrame(self.mylist)
            df.rename(columns=datacol,inplace=True)
            df.to_excel('火车票数据7.xlsx')
        except Exception as e:
            df = pd.DataFrame(self.mylist)
            df.rename(columns=datacol,inplace=True)
            df.to_excel('火车票数据7.xlsx')
            raise
    

if __name__ == '__main__':
    xc_demo().start()